<template>
  <!--主页-->
  <div class="main">
    <div class="main-head">
      <img src="./../assets/logo-home.png" draggable="false">
      <el-dropdown>
        <el-avatar :src="avatarUrl" shape="square"/>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item>
            <el-upload class="upload-demo" ref="upload" :action="avatarAction"
                       :show-file-list="false" :auto-upload="true" :with-credentials="true" :on-success="updateAvatarSuccess">
              <i class="el-icon-setting"/>
              <el-button type="text">更换头像</el-button>
            </el-upload>
          </el-dropdown-item>
          <el-dropdown-item>
            <i class="el-icon-share"/>
            <el-link :underline="false" href="/#/share">
              <el-button type="text">下载分享</el-button>
            </el-link>
          </el-dropdown-item>
          <el-dropdown-item>
            <i class="el-icon-warning"/>
            <el-link :underline="false" href="/#/setting-s">
              <el-button type="text">账号安全</el-button>
            </el-link>
          </el-dropdown-item>
          <el-dropdown-item>
            <i class="el-icon-switch-button"/>
            <el-button type="text" @click="logout()">退出登录</el-button>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <div class="main-operation">
      <ul>
        <li><el-button icon="el-icon-upload" type="warning" round @click="up()">上传</el-button></li>
        <li><el-button icon="el-icon-bottom" type="primary" round @click="down()">下载</el-button></li>
        <li><el-button icon="el-icon-folder-add" type="success" round @click="mkdir()">新建文件夹</el-button></li>
        <li><el-button icon="el-icon-scissors" type="info" round @click="moveDrawer = true">移动</el-button></li>
        <li><el-button icon="el-icon-delete" type="danger" round @click="del()">删除</el-button></li>
        <li><el-button icon="el-icon-share" type="info" round @click="share()">分享</el-button></li>
        <li><el-button icon="el-icon-search" type="success" round @click="searchDrawer = true">搜索网盘</el-button></li>
        <li><el-button icon="el-icon-refresh" type="primary" round @click="refresh()">刷新</el-button></li>
        <li>
          <el-badge :value="value">
            <el-button icon="el-icon-bell"  type="warning" round @click="adviceDrawer = true">通知</el-button>
          </el-badge>
        </li>
      </ul><br/>
      <!--移动抽屉-->
      <el-drawer class="move-drawer" :visible.sync="moveDrawer" direction="ttb" size="62%" :before-close="moveDrawerClose">
        {{this.moveDrawerCurrentPath}}
        <el-table class="move-drawer-table" :data="moveDrawerTableData" stripe height="300">
          <el-table-column prop="dir">
            <template slot-scope="scope">
              <el-button type="text" @click="getMoveCurrentPath(scope.row.dir)">{{scope.row.dir}}</el-button>
            </template>
          </el-table-column>
        </el-table><br/>
        <el-button round @click="move()">确定移动</el-button>
      </el-drawer>
      <!--搜索网盘抽屉-->
      <el-drawer class="search-drawer" :visible.sync="searchDrawer" direction="ttb" size="80%" :before-close="searchDrawerClose">
        <el-input class="search-drawer-input" placeholder="关键字" v-model="searchDrawerInput"/>
        <el-button round icon="el-icon-search" @click="search()"/>
        <!--搜索表格-->
        <el-table class="search-drawer-table" :data="searchDrawerTableData" stripe height="480" :border="true">
          <el-table-column prop="filename" width="210px" label="文件名"/>
          <el-table-column prop="path" width="580px" label="文件路径">
            <template slot-scope="scope">
              <el-button type="text" @click="getSearchPathFile(scope.row.path)">{{scope.row.path}}</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="modified" width="210px" label="修改时间"/>
        </el-table>
      </el-drawer>
      <!--通知抽屉-->
      <el-drawer title="通知" :visible.sync="adviceDrawer" direction="rtl" size="50%" :before-close="adviceDrawerClose">
        <el-button type="text" @click="writeAll()">一键已读</el-button>
        <el-button type="text" @click="deleteAll()">一键清除</el-button>
        <!--通知分页表格-->
        <el-table :data="adviceDrawerTableData" @expand-change="expandChange" height="500">
          <el-table-column type="expand" prop="content">
            <template slot-scope="scope">
              <span>{{scope.row.content}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="created" width="300px"/>
          <el-table-column prop="title" width="300px"/>
          <el-table-column prop="isRead">
            <template slot-scope="scope">
              <template v-if="scope.row.isRead === 0">未读</template>
              <template v-else>已读</template>
            </template>
          </el-table-column>
        </el-table><br/><br/>
        <!--通知分页-->
        <el-pagination background layout="prev, pager, next" :total="100" @current-change="currentPage"/>
      </el-drawer>
    </div>
    <div class="main-breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <template v-for="(item, i) in currentPathArray">
          <el-breadcrumb-item>
            <el-button type="text" @click="getBreadcrumbFile(i)">{{item}}</el-button>
          </el-breadcrumb-item>
        </template>
      </el-breadcrumb>
    </div><br/>
    <div class="main-table">
      <el-table ref="multipleTable" height="380" :data="tableData"
                stripe tooltip-effect="dark" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="type" label="文件类型" width="120">
          <template slot-scope="scope">
            <span v-show="scope.row.type === 'directory'">
              <i class="el-icon-folder"/>
            </span>
            <span v-show="scope.row.type === 'file'">
              <i class="el-icon-tickets"/>
            </span>
            <span v-show="scope.row.type === 'image_file'">
              <i class="el-icon-picture"/>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="filename" label="文件名">
          <template slot-scope="scope">
            <span v-if="isRename[scope.$index] === true">
                <el-input style="width:70%" v-model="newFilename"></el-input>
                <el-button icon="el-icon-check" type="text" @click="submitRename(scope.$index, scope.row)"/>
                <el-button icon="el-icon-close" type="text" @click="closeRename(scope.$index, scope.row)"/>
            </span>
            <span v-else>
              <span v-show="scope.row.type === 'directory'">
                <el-button type="text" @click="getFilenameFile(scope.row.filename)">{{scope.row.filename}}</el-button>
              </span>
              <span v-show="scope.row.type === 'image_file'">
                <el-button type="text" @click="image(scope.row.filename)">{{scope.row.filename}}</el-button>
              </span>
              <span v-show="scope.row.type === 'file'">{{scope.row.filename}}</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="size" label="大小" width="180">
          <template slot-scope="scope">
            {{scope.row.size}}
          </template>
        </el-table-column>
        <el-table-column prop="modified" label="更新时间" width="200"/>
        <el-table-column width="100">
          <template slot-scope="scope">
            <el-button size="mini" @click="rename(scope.$index, scope.row)">重命名</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="main-power">
      © 2021 Powered by zsc ccying
    </div>
  </div>
</template>

<style>
  .main {
    margin: auto;
    width: 80%;
  }
  .main-operation {
    padding-left: 0%;
  }
  .main-operation ul {
    list-style-type: none;
    margin:0;
    padding:0;
  }
  .main-operation li {
    display: inline;
  }
  .main-breadcrumb {
    margin: auto;
    width: 80%;
  }
  .main-table {
    margin: auto;
    width: 80%;
  }
  .main-power {
    padding-top: 100px;
  }
  .search-drawer-input {
    width: 440px;
  }
  .move-drawer {
    margin: auto;
    width: 600px;
  }
  .search-drawer {
    margin: auto;
    width: 1000px;
  }
</style>

<script>
  export default {
    data() {
      let user = JSON.parse(sessionStorage.getItem('user'));
      let {uid:uid} = user;
      return {
        /** main-head */
        uid: uid,
        //头像url
        avatarUrl: this.$http.defaults.baseURL + 'file/getImage/' + uid + ".png/0",
        //上传头像链接
        avatarAction: this.$http.defaults.baseURL + "reset-avatar",

        /** main-operation */
        //移动抽屉
        moveDrawer: false,
        //移动抽屉当前路径
        moveDrawerCurrentPath: '',
        //移动抽屉表格属性
        moveDrawerTableLabel: [
          { prop: 'dir', label: '文件夹'}
        ],
        //移动抽屉表格数据
        moveDrawerTableData: [],
        //搜索抽屉
        searchDrawer: false,
        //搜索抽屉关键字输入框
        searchDrawerInput: '',
        //搜索抽屉表格属性
        searchDrawerTableLabel: [
          { prop: 'filename', label: '文件名' },
          { prop: 'path', label: '文件路径' },
          { prop: 'modified', label: '文件修改时间'}
        ],
        //搜索抽屉表格数据
        searchDrawerTableData: [],
        //通知未读数量
        value: '',
        //通知抽屉
        adviceDrawer: false,
        //通知抽屉表格属性
        adviceDrawerTableLabel: [
          { prop: 'title', label: '通知标题' },
          { prop: 'content', label: '通知内容' },
          { prop: 'created', label: '通知时间' },
          { prop: 'isRead', label: '是否已读' }
        ],
        //通知抽屉表格数据
        adviceDrawerTableData: [],

        /** main-breadcrumb */
        //当前路径
        currentPath: '',
        //当前路径数组，根据当前路径切割目分隔符得来
        currentPathArray: [],

        /** main-table */
        //表格所选记录项
        multipleSelection: [],
        //表格所选记录项标准文件名，文件名含有当前路径
        multipleSelectionFilename: [],
        //表格属性
        tableLabel: [
          { prop: 'filename', label: '文件名'},
          { prop: 'path', label: '文件路径'},
          { prop: 'type', label: '文件类型'},
          { prop: 'size', label: '文件大小'},
          { prop: 'modified', label: '文件修改时间'}
        ],
        //表格记录数据
        tableData: [],
        //标记是否重命名操作
        isRename: [],
        //文件重命名输入
        newFilename: '',
      }
    },
    methods: {
      /** main-head */
      //修改文件头像成功
      updateAvatarSuccess() {
        this.$router.push("/home");
      },
      //退出登录
      logout() {
        this.$http({
          method: 'post',
          url: '/logout'
        }).then(res=>{
          sessionStorage.removeItem('user');
          this.$router.push('/');
          location.reload();
        })
      },

      /** main-operation */
      //上传
      up() {
        sessionStorage.setItem('currentPath', this.currentPath);
        this.$router.push("/up");
      },
      //下载
      down() {
        let type = 0;
        this.toZip(type).then(res => {
           this.refresh();
          console.log(1)
          let type = 0;
          let urls = this.$http.defaults.baseURL + "file/download/" + res + "/" + type;
          window.location.href = urls;
          // window.open(urls, '_blank');
          debugger
        })
      },
      //新建文件夹
      mkdir() {
        this.$http({
          method: 'post',
          url: '/file/mkdir',
          data: this.$qs.stringify({
            path: this.currentPath
          })
        }).then(res => {
          let {code} = res.data;
          if (code === 1000) {
            //未登录
            sessionStorage.removeItem('user');
            this.$router.push('/');
          } else {
            this.refresh();
          }
        })
      },
      //移动
      getMovePath(path) {
        this.moveDrawerCurrentPath = path;
        this.$http({
          method: 'post',
          url: '/file/getCurrentDirName/',
          data: this.$qs.stringify({
            path: this.moveDrawerCurrentPath
          })
        }).then(res => {
          let data = res.data.data;
          this.moveDrawerTableData = [];
          for (let i = 0; i < data.length; i++) {
            this.moveDrawerTableData[i] = { dir:data[i] };
          }
        })
      },
      getMoveCurrentPath(dir) {
        let path = this.moveDrawerCurrentPath + '/' + dir;
        this.getMovePath(path);
      },
      moveDrawerClose(done) {
        this.getMovePath(this.uid);
        //清楚表格所选项
        this.multipleSelectionFilename = [];
        done();
      },
      move() {
        this.getSelectionFilename();
        this.$http({
          method: 'post',
          url: '/file/move',
          data: this.$qs.stringify({
            sources: this.multipleSelectionFilename,
            target: this.moveDrawerCurrentPath,
          }, { arrayFormat: 'repeat' })
        }).then(res=>{
          this.moveDrawer = false;
          this.getMovePath(this.uid);
          this.refresh();
        })
      },
      //删除
      del() {
        this.getSelectionFilename();
        this.$http({
          method: 'post',
          url: '/file/delete',
          data: this.$qs.stringify({
             paths: this.multipleSelectionFilename
            }, { arrayFormat: 'repeat' }),
        }).then(res => {
          let {code} = res.data;
          if (code === 1000) {
            //未登录
            sessionStorage.removeItem('user');
            this.$router.push('/');
          } else {
            this.refresh();
          }
        })
      },
      //分享
      share() {
        //进行文件分享压缩
        let type = 1;
        this.toZip(type).then(res=>{
          this.$http({
            method: 'get',
            url: '/file/share/' + res,
          }).then(res=>{
            let {code} = res.data;
            if (code === 1000) {
              //未登录
              sessionStorage.removeItem('user');
              this.$router.push('/');
            } else {
              this.refresh();
            }
          })
        });
      },
      //搜索
      search() {
        this.$http({
          method: 'get',
          url: '/file/search/' + this.searchDrawerInput
        }).then(res=>{
          let {code} = res.data;
          if (code === 1000) {
            //未登录
            sessionStorage.removeItem('user');
            this.$router.push('/');
          } else {
            this.searchDrawerTableData = res.data.data;
          }
        })
      },
      searchDrawerClose(done) {
        this.searchDrawerInput = '';
        this.searchDrawerTableData = [];
        done();
      },
      getSearchPathFile(path){
        this.currentPath = path;
        this.getFile();
        this.searchDrawer = false;
      },
      //刷新
      refresh() {
        //请求当前目录文件
        this.getFile();
        //请求通知
        this.advise(0, 10);
      },
      //通知
      advise(offset, row) {
        this.$http({
          method: 'get',
          url: '/advise/get/' + offset + "/" + row
        }).then(res=>{
          let {code} = res.data;
          if (code === 1000) {
            //未登录
            sessionStorage.removeItem('user');
            this.$router.push('/');
          } else {
            this.value = '';
            this.adviceDrawerTableData = res.data.data;
            for (let i = 0; i < this.adviceDrawerTableData.length; i++) {
              if (this.adviceDrawerTableData[i].isRead === 0) {
                this.value++;
              }
            }
          }
        })
      },
      adviceDrawerClose(done) {
        done();
        this.refresh();
      },
      writeAll() {
        this.$http({
          method: 'get',
          url: '/advise/isRead'
        }).then(res=>{
          //刷新，重新获取通知
          this.advise(0, 10);
        })
      },
      deleteAll() {
        this.$http({
          method: 'get',
          url: '/advise/delete'
        }).then(res=>{
          //刷新，重新获取通知
          this.advise(0, 10);
        })
      },
      expandChange(row, expandedRows) {
        //通知ID
        let id = row.id;
        this.$http({
          method: 'get',
          url: '/advise/isRead/' + id
        }).then(res=>{
          //已读
          row.isRead = 1;
        })
      },
      currentPage(page) {
        let offset = (page - 1) * 10;
        this.advise(offset, 10);
      },

      /** breadcrumb */
      //获取导航路径文件
      getBreadcrumbFile(index) {
        this.currentPath = '';
        //严格控制最后路径名不带文件分隔符
        for (let i = 0; i < index; i++) {
          this.currentPath = this.currentPath + this.currentPathArray[i] + '/';
        }
        this.currentPath = this.currentPath + this.currentPathArray[index];

        this.getFile();
      },

      /** main-table */
      //表格所选项
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      //获取所选表格文件路径名
      getSelectionFilename() {
        for (let i = 0; i < this.multipleSelection.length; i++) {
          this.multipleSelectionFilename[i] = this.currentPath + '/' + this.multipleSelection[i].filename;
        }
      },
      //进入表格文件夹获取文件
      getFilenameFile(filename) {
        this.currentPath = this.currentPath + "/" + filename;
        this.getFile();
      },
      //预览图片
      image(filename) {
        let href = this.$http.defaults.baseURL + "file/getImage/" + filename + "/1";
        window.open(href, '_blank', 'toolbar=yes, width=900, height=700')
      },
      //重命名
      rename(index, row) {
        this.$set(this.isRename, index, true)
      },
      submitRename(index, row) {
        let source = this.currentPath + "/" + row.filename;
        let target = this.currentPath + "/" + this.newFilename;
        console.log(source)
        console.log(target)
        this.$http({
          method: 'post',
          url: '/file/rename',
          data: this.$qs.stringify({
            source: source,
            target: target
          })
        }).then(res => {
          //结束重命名状态
          this.$set(this.isRename, index, false);
          //清除文件重命名输入
          this.newFilename = '';
          //刷新
          this.refresh();
        })
      },
      closeRename(index, row) {
        this.$set(this.isRename, index, false);
      },

      //获取用户根目录文件
      getRootFile() {
        this.$http({
          method: 'get',
          url: '/file/getCurrentRootPathFiles'
        }).then(res=>{
          let {code, message, data} = res.data;
          if (code === 1000) {
            //未登录
            sessionStorage.removeItem('user');
            this.$router.push('/');
          } else {
            this.tableData = data;
            //防止用户主目录未创建出现异常
            let user = JSON.parse(sessionStorage.getItem('user'));
            let {uid:uid} = user;
            this.currentPath = uid;
            this.currentPathArray[0] = uid;
          }
        })
      },
      //获取用户当前目录文件
      getFile() {
        this.$http({
          method: 'post',
          url: '/file/getCurrentPathFiles',
          data: this.$qs.stringify({
            path: this.currentPath
          })
        }).then(res => {
          let {code, message, data} = res.data;
          if (code === 1000) {
            //未登录
            sessionStorage.removeItem('user');
            this.$router.push('/');
          } else {
            //赋值表格记录数据
            this.tableData = data;
            //表格记录数据数
            let size = this.tableData.length;
            //赋值当前路径数组
            this.currentPathArray = this.currentPath.split(/[/\\]/);
            //赋值标记不需要重命名操作
            for (let i = 0; i < size; i++) {
              this.rename[i] = false;
            }
            //清除表格所选名字
            this.multipleSelectionFilename = [];
          }
        })
      },
      //压缩文件
      toZip(type) {
        this.getSelectionFilename();
        return new Promise((resolve, reject) => {
          this.$http({
              method: 'post',
              url: '/file/zip/' + type,
              data: this.$qs.stringify({
              paths: this.multipleSelectionFilename
            }, { arrayFormat: 'repeat' }),
          }).then(res => {
            let {code} = res.data;
            if (code === 1000) {
              //未登录
              sessionStorage.removeItem('user');
              this.$router.push('/');
            } else {
              resolve(res.data.data);
            }
          })
        });
      }
    },
    created() {
      this.getRootFile();
      this.getMovePath(this.uid);
      this.advise(0, 10);
    }
  }
</script>
